package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * 菜单管理控制层
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    /**
     * 获取菜单 从getMenus获取用户数据
     *
     * @return
     */
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MenuService menuService;

    @RequestMapping(value = "/getMenus", method = RequestMethod.GET)
    public Result getMenus() {
        try {
            //获取用户名，进入redis查找
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            String userRedis = jedisPool.getResource().get(username);
            //            List<Menu> menus = new ArrayList<>();
            //            Map<String, Object> map=new HashMap<>();
            List<Menu> listMenu = JSON.parseObject(userRedis, new TypeReference<List<Menu>>() {
            });
//            List<Menu> listMenu = JSON.parseObject(userRedis, new TypeReference<List<Menu>>());
            if (listMenu == null) {
                listMenu = menuService.getMenus(username);
                jedisPool.getResource().setex(username, 60 * 10, JSON.toJSONString(listMenu));
            }

            return new Result(true, MessageConstant.GET_MENU_SUCCESS, listMenu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_FAIL);
        }
    }


}
